package nl.zeeman.planner;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

//import android.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class divetable extends Activity implements OnClickListener, Runnable {
	private final String COL_TABLE_DATE = "diveDate";
	private final String COL_TABLE_HT = "high";
	private final String COL_TABLE_LT = "low";
	private final String COL_TABLE_MOON = "MoonPhase";
	
	private final String COL_DATE_MAX = "max";
	private final String COL_DATE_MIN = "min";
	
	private final int MSG_THREAD_FINISHED = 0;
	private final int MSG_ADD_ROW = 1;
	private final int MSG_CLEAR_TABLE = 3;

	private final int COLINDEX_DATE = 0;
	private final int COLINDEX_HT = 1;
	private final int COLINDEX_LT = 2;
	private final int COLINDEX_MOON = 3;
	
	private TableLayout mTable;

	private TextView mColDate;
	private TextView mColHT;
	private TextView mColLT;
	private TextView mColMoon;
	
	private Button mPrev;
	private Button mNext;
	private Button mAll;
	private boolean mShowAll;
	
	private int mYear;
	private int mMonth;
	private int mSelYear, mSelMonth;

	private int mMinYear, mMaxYear;
	private int mMinMonth, mMaxMonth;
	
	private PlannerDatabaseAdapter myDBHelper;

	ProgressDialog dialog;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.divetable);
        
        // somehow using the parent's database doesn't work
        myDBHelper = new PlannerDatabaseAdapter(this);
        myDBHelper.open();

        //get UI handles
        mTable = (TableLayout) findViewById(R.id.tblDive);
        
        mColDate = (TextView) findViewById(R.id.colDate);
        mColHT= (TextView) findViewById(R.id.colHT);
        mColLT= (TextView) findViewById(R.id.colLT);
        mColMoon= (TextView) findViewById(R.id.colMoon);
        mPrev = (Button) findViewById(R.id.btnPrev);
        mNext = (Button) findViewById(R.id.btnNext);
        mAll = (Button) findViewById(R.id.btnAll);
        mShowAll = true;
        
        mPrev.setOnClickListener(this);
        mNext.setOnClickListener(this);
        mAll.setOnClickListener(this);
        
        getMinMax();
        
        Calendar cal = Calendar.getInstance();
        mYear = cal.get(Calendar.YEAR);
        mMonth = cal.get(Calendar.MONTH);

        mYear = planner.mYear;
        mMonth = planner.mMonth;
        
        FillTable();
	}
	
	public void onResume(){
		super.onResume();
		
        myDBHelper = new PlannerDatabaseAdapter(this);
        myDBHelper.open();
		
	}

	public void onStop(){
		super.onStop();
		
		dialog.dismiss();

		myDBHelper.close();
		
	}
	
	public void onClick(View v){
		//logic to enable and disable buttons if we reach the first
		//or last available month
		if (v==mNext){
			if(mMonth==11){
				mMonth = 0;
				mYear++;
			} else {
				mMonth++;
			}
			FillTable();
		}
		if(v==mPrev){
			if (mMonth==0){
				mMonth = 11;
				mYear--;
			}else{
				mMonth--;
			}
			FillTable();
		}
		if(v==mAll){
			if (mShowAll){
				mSelYear = mYear;
				mSelMonth = mMonth;
				mMonth = -1;
				mYear = 0;
				FillTable();
			}else{
				mMonth = mSelMonth;
				mYear = mSelYear;
				FillTable();
			}
			mShowAll = !mShowAll;
		}
	}
	
	private void FillTable( ){

		// show the progress dialog
		dialog = ProgressDialog.show(divetable.this, "", 
                "Loading. Please wait...", true);

		//temporarily hide the table to speed up processing
		mTable.setVisibility(8);
		
		// start processing in a new thread, otherwise
		// the dialog won't show
		Thread thread = new Thread(divetable.this);
		thread.start();
		
		if (mYear == 0) {
			mPrev.setEnabled(false);
			mNext.setEnabled(false);
			mAll.setText(R.string.lblMonth);
		}else {
			mAll.setText(R.string.lblAlles);
			if (mYear==mMinYear && mMonth==mMinMonth){
	     		mPrev.setEnabled(false);
	     	}else{
	     		mPrev.setEnabled(true);
	     	}
	     	if (mYear==mMaxYear && mMonth==mMaxMonth){
	     		mNext.setEnabled(false);
	     	}else{
	     		mNext.setEnabled(true);
	     	}
		}
	}

	//function to add a row to the dive table
	private void AddDiveRow(String date, String ht, String lt, String moon) {
    	
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new TableRow.LayoutParams(
        		TableRow.LayoutParams.FILL_PARENT,
        		TableRow.LayoutParams.WRAP_CONTENT));  
        
        if (date == null){
        	View v = new View(this);
        	v.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 2));
        	v.setBackgroundColor(0xFF909090);
        } else {
        	
	        // add columns to tablerow
	        TextView tx = new TextView(this);
	        tx.setText(date);
	        tx.setGravity(Gravity.RIGHT);
	        tx.setPadding(3, 0, 6, 0);
	        tx.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
	                							TableRow.LayoutParams.WRAP_CONTENT));
	        tx.setLayoutParams(new TableRow.LayoutParams(1));
	        tr.addView(tx);
	        tx = new TextView(this);
	        tx.setText(ht);
	        tx.setGravity(Gravity.RIGHT);
	        tx.setPadding(6, 0, 6, 0);
	        tx.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
	        											 TableRow.LayoutParams.WRAP_CONTENT));
	        tx.setLayoutParams(new TableRow.LayoutParams(2));
	        tr.addView(tx);
	        tx = new TextView(this);
	        tx.setText(lt);
	        tx.setGravity(Gravity.RIGHT);
	        tx.setPadding(6, 0, 6, 0);
	        tx.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
														 TableRow.LayoutParams.WRAP_CONTENT));
	        tx.setLayoutParams(new TableRow.LayoutParams(3));
	        tr.addView(tx);
	        tx = new TextView(this);
	        tx.setText(moon);
	        tx.setGravity(Gravity.LEFT);
	        tx.setPadding(6, 0, 3, 0);
	        tx.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT,
	        											 TableRow.LayoutParams.WRAP_CONTENT));
	        tx.setLayoutParams(new TableRow.LayoutParams(4));
	        tr.addView(tx);
        }
        
        //add row to table
        // this can only be done in the calling thread, so we
        // leave a message there
        Message m = new Message();
        m.what = MSG_ADD_ROW;
        m.obj = tr;

        handler.sendMessage(m);
        
    }
    
	// get the first and last dates in the dive table
	private void getMinMax(){
    	Cursor c = myDBHelper.GetDateLimits();
    	
     	if (c == null){
     		finish();
     	} else {
     		if (c.moveToFirst()) {
	     		
	     		int maxdateCol = c.getColumnIndex(COL_DATE_MAX);
	     		int mindateCol = c.getColumnIndex(COL_DATE_MIN);
	     		
	     		String min = c.getString(mindateCol);
	     		String max = c.getString(maxdateCol);
	     		
	     		//assumes format yyyy-mm-dd
	     		mMinYear = Integer.parseInt(min.substring(0,4));
	     		mMinMonth = Integer.parseInt(min.substring(5,7))-1;
	     		mMaxYear = Integer.parseInt(max.substring(0,4));
	     		mMaxMonth = Integer.parseInt(max.substring(5,7))-1;     		
     		}
     		c.close();
     	}
    }

    // automatically starts when a new thread is created
    // used for update the table
    public void run() {

		Cursor c = myDBHelper.GetDiveTable(mYear, mMonth+1);
     	if (c == null){
     		finish();
     	} else {
     		int DateColumn = c.getColumnIndex(COL_TABLE_DATE);
     		int HTColumn = c.getColumnIndex(COL_TABLE_HT);
     		int LTColumn = c.getColumnIndex(COL_TABLE_LT);
     		int MoonColumn = c.getColumnIndex(COL_TABLE_MOON);
     		if (c.moveToFirst()) {
     			if (mTable.getChildCount() > 0 ){
     				handler.sendEmptyMessage(MSG_CLEAR_TABLE);
     			}
	     		String oldDate = null;
	     		String oldHT = null;
	     		String oldLT = null;
	     		do {
	     			String date = c.getString(DateColumn);
	     			String ht = c.getString(HTColumn);
	     			String lt = c.getString(LTColumn);
	     			String moon = c.getString(MoonColumn);
	     			     			
	     			if (date.equals(oldDate)){
	     				date = "";
	     				if (ht.equals(oldHT)) {
	     					ht = "";
	     				}
	     				if (lt.equals(oldLT)){
	     					lt = "";
	     				}     				
	     			}
	     			if (moon.length() != 2){
	     				moon = "";
	     			}
	     			
	     			if (date.length() > 0 ){
	         			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	         			try {
							Date d = df.parse(date);
							df.applyPattern("E d-M-yyyy");
							date = df.format(d);
						} catch (ParseException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	     			}
	     			     			
	     			AddDiveRow(date, ht, lt, moon);
	
	     			oldDate = c.getString(DateColumn);
	     			oldHT = c.getString(HTColumn);
	     			oldLT = c.getString(LTColumn);
	     			
	     			
	     		} while (c.moveToNext());
	     		c.close();
     		}
     	}
		
     	// tell the calling thread we've finished
     	handler.sendEmptyMessage(MSG_THREAD_FINISHED);
    }
	
    // handler for messages from the child-thread
    // used for updating UI elements (can't be done from the
    // child thread)
    final Handler handler = new Handler() {

    	@Override
		public void handleMessage(Message msg){
	    	super.handleMessage(msg);

	    	switch (msg.what) {
			case MSG_THREAD_FINISHED:
				mTable.setVisibility(0);
				
				// update the widths of the table header to match the 
				// widths of the columns
				TableRow r = (TableRow)mTable.getChildAt(0);
				mColDate.setWidth(r.getChildAt(COLINDEX_DATE).getWidth());
				mColHT.setWidth(r.getChildAt(COLINDEX_HT).getWidth());
				mColLT.setWidth(r.getChildAt(COLINDEX_LT).getWidth());
				mColMoon.setWidth(r.getChildAt(COLINDEX_MOON).getWidth());
				
				if (dialog.isShowing()){
					// if we use dismiss here, the next time we show and dismiss
					// the dialog the app crashes
					// so we hide it here, and only dismiss it at activity end
					dialog.hide();
				}

				break;

			case MSG_ADD_ROW:
		        mTable.addView((TableRow)msg.obj, new TableLayout.LayoutParams(
		                TableLayout.LayoutParams.FILL_PARENT,
		                TableLayout.LayoutParams.WRAP_CONTENT));
		        break;
			case MSG_CLEAR_TABLE:
				mTable.removeAllViews();
//				mTable.removeViews(2, mTable.getChildCount()-2);
				break;
			default:
				break;
			}
		}
	};
}
